package br.pucrs.prototipoonline.action;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;

import br.pucrs.prototipoonline.exceptions.POApplicationException;
import br.pucrs.prototipoonline.facade.BaseFacade;
import br.pucrs.prototipoonline.vo.UsuarioVO;



/**
 * 
 * @author Ricardo Luckei
 * @author Gelson Gentil
 *
 */
public abstract class POBaseAction extends Action {
	private static Logger logger = Logger.getLogger(POBaseAction.class);
	protected static final String USUARIO_VO = "UsuarioVO";
	protected UsuarioVO usuarioVO = null;
	

	protected final void setUsuario(HttpServletRequest request, UsuarioVO vo) {
		request.getSession().setAttribute(USUARIO_VO, vo);
		if(this.usuarioVO == null) {
			this.usuarioVO = vo;
		}
	}
	
	protected final UsuarioVO getUsuario(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object usuVO = session.getAttribute(USUARIO_VO);
		return (UsuarioVO) usuVO;
	}

	
	protected String convertISO555912UTF8(String str) {
		
		try {
			logger.debug("Convertendo para utf-8 a string: "+ str);
			byte[] stringBytesISO = str.getBytes("ISO-8859-1");
			String ret = new String(stringBytesISO, "UTF-8");
			logger.debug("convertido: " + ret);
			return ret;
		} catch (UnsupportedEncodingException e) {
			logger.error("Erro convertendo a string para utf-8");
			return str;
		}
	}
	
	/**
	 * retorna instancia de uma facade
	 * @param facadeClass
	 * @return
	 * @throws POApplicationException 
	 */
	protected Object getFacade(Class<? extends BaseFacade> facadeClass) throws POApplicationException {
		try {
			Constructor<? extends BaseFacade> contructor = facadeClass.getConstructor(new Class[]{UsuarioVO.class});
			return contructor.newInstance(new Object[]{usuarioVO});
		} catch (Exception e) {
			e.printStackTrace();
			String cause = e.getCause() != null ? e.getCause().getMessage() : "";
			throw new POApplicationException("Erro ao criar facade " + facadeClass.getName() + " - " + cause);
		}
	}
}
